package com.it.tydic.estate.module.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.it.tydic.estate.common.aop.CodeMsg;
import com.it.tydic.estate.common.aop.Result;
import com.it.tydic.estate.common.util.*;
import com.it.tydic.estate.module.mapper.inner.GuanlichuMapper;
import com.it.tydic.estate.module.mapper.inner.LouyuMapper;
import com.it.tydic.estate.module.model.inner.Guanlichu;
import com.it.tydic.estate.module.model.inner.Louyu;
import com.it.tydic.estate.module.service.FJglService;
import com.it.tydic.estate.module.service.LouyuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.annotation.Resource;
import java.util.*;

/**
 * 楼宇管理实现接口实现类
 */
@Service
@Transactional
public class LouyuServiceImpl implements LouyuService {
    @Autowired
    private LouyuMapper louyuMapper;//楼宇
    @Autowired
    private FJglService fJglService;//房间信息
    @Resource
    private GuanlichuMapper guanlichuMapper;////小区
    /**
     * 楼宇添加或修改
     *
     * @param louyu
     * @return
     */
    @Override
    public Result addOrUpload(Louyu louyu) {
        if(StringUtil.isEmpty(louyu.getXqid())||StringUtil.isEmpty(louyu.getLymc())
                || StringUtil.isEmpty(louyu.getLybh())){//参数非空验证
            return  Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        String userId= CurrentUtil.getCurrentUserId();
        if (louyu.getId() == null || "".equals(louyu.getId())) {//判断是否有主键
            long id = new InstaIdGenerator().nextId(TimeUtil.timeGen());//生成Id主键
           if(checkCode(louyu.getXqid(), louyu.getLybh()))//小区编码验重
               return  Result.error(CodeMsg.DATA_REPEATE);
            louyu.setId(String.valueOf(id));
            louyu.setCjsj(new Date());
            louyu.setXgsj(new Date());
            louyu.setZfbj(ZfbjFinalUtil.zfbj_zy);
            louyu.setCuserId(userId);
            int result = louyuMapper.insertSelective(louyu);
            if (result < 0)
                return Result.error(CodeMsg.INTER_ERROR);
        } else {
            louyu.setXgsj(new Date());
            louyu.setUuserId(userId);
            int result = louyuMapper.updateByPrimaryKeySelective(louyu);
            if (result < 0){
                return Result.error(CodeMsg.UPDATE_ERROR);
            }
        }
        return Result.success(louyu.getId());
    }

    /**
     * 楼宇条件查询
     *
     * @param louyuMap
     * @return
     */
    @Override
    public Result queryList(Map<String, Object> louyuMap) {
        Map<String, Object> map = new HashMap<>();
        if (louyuMap.containsKey("pageNum") && louyuMap.containsKey("pageSize")) {//判断是否有分页条件有进行分页
            PageHelper.startPage((Integer) louyuMap.get("pageNum"), (Integer) louyuMap.get("pageSize"));
        }else{
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        Page<Louyu> louyus = louyuMapper.selectList(louyuMap);

        List<Louyu> result = louyus.getResult();
        if(result.size()>0){
            Map<String, String> villages = fJglService.villageMap();//小区信息
            for (Louyu louyu:result) {
                if (villages.containsKey(louyu.getXqid())) {//获取小区名称
                    louyu.setXqmc(villages.get(louyu.getXqid()));
                } else {
                    louyu.setXqmc("");
                }
            }
        }
        map.put("result", result);
        map.put("totle", louyus.getTotal());
        return Result.success(map);
    }

    /**
     * 根据主键删除楼宇
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteById(String id) {
        if (!StringUtils.isNotEmpty(id))//非空校验
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        Louyu louyu = new Louyu();
        louyu.setId(id);
        louyu.setZfbj(ZfbjFinalUtil.zfbj_zf);
        int result = louyuMapper.updateByPrimaryKeySelective(louyu);
        if (result <= 0)
            return Result.error(CodeMsg.DELETE_ERROR);
        ArrayList<String> objects = new ArrayList<String>();
        objects.add(id);
        fJglService.deleteBatchByXqid("0",objects);//删除房间信息
        return Result.success();
    }

    /**
     * 批量删除
     *
     * @param list
     * @return
     */
    @Override
    public Result deleteBatch(List<String> list) {
        if (list == null || list.size() <= 0)//非空校验
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        Example example = new Example(Louyu.class);
        example.createCriteria().andIn("id", list);
        Louyu louyu = new Louyu();
        louyu.setZfbj(ZfbjFinalUtil.zfbj_zf);
        int result = louyuMapper.updateByExampleSelective(louyu, example);
        if (result <= 0)
            return Result.error(CodeMsg.DELETE_ERROR);
        fJglService.deleteBatchByXqid("0",list);//删除房间信息
        return Result.success();
    }

    /**
     * 根据小区主键删除小区信息
     *
     * @param list 小区主键集合
     * @return
     */
    @Override
    public Result deleteBatchByXqid(List<String> list) {
        if (list == null || list.size() <= 0)//非空校验
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        Example example = new Example(Louyu.class);
        example.createCriteria().andIn("xqid", list);
        Louyu louyu = new Louyu();
        louyu.setZfbj(ZfbjFinalUtil.zfbj_zf);
        int result = louyuMapper.updateByExampleSelective(louyu, example);
        fJglService.deleteBatchByXqid("1",list);//删除房间信息
       return  Result.success();
    }

    /**
     * 根据主键查询楼宇
     * @param id
     * @return
     */
    @Override
    public Result queryById(String id) {
        if (!StringUtils.isNotEmpty(id))//非空校验
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        Louyu louyu = louyuMapper.selectByPrimaryKey(id);
        if(louyu==null){
            return Result.error(CodeMsg.DATA_NOT_EXIST);
        }
        return Result.success(louyu);
    }

    /**
     * 根据小区主键查楼宇
     * @param id
     * @return
     */
    @Override
    public Result queryByLyId(String id) {
        if (!StringUtils.isNotEmpty(id))//非空校验
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        Example example = new Example(Louyu.class);
        example.createCriteria().andEqualTo("xqid", id).andEqualTo("zfbj",ZfbjFinalUtil.zfbj_zy);
        List<Louyu> louyus = louyuMapper.selectByExample(example);
        return Result.success(louyus);
    }

    /**
     * 验证编码楼宇编码是否重复
     * @param code
     * @return
     */
    private boolean checkCode(String xqid,String code) {
        boolean flag =false;
        Example example = new Example(Louyu.class);
        example.createCriteria().andEqualTo("xqid", xqid).andEqualTo("lybh", code).andEqualTo("zfbj", ZfbjFinalUtil.zfbj_zy);
        int num = louyuMapper.selectCountByExample(example);
        if (num > 0)
            flag=true;
        return flag;
    }

    /**
     * 楼宇添加小区名称
     * @param louyu
     */
    private void addName(Louyu louyu){
        Guanlichu guanlichu = guanlichuMapper.selectByPrimaryKey(louyu.getXqid());
        if(guanlichu!=null){
            louyu.setXqmc(guanlichu.getName());
        }
    }

}
